/*
 * @Descripttion   : 优化的Outline后期处理类，支持多个独立实例
 * @version        : 2.0
 * @Author         :
 * @Date           : 2025-09-17 17:00
 * @LastEditTime   : 2025-09-18 13:27
 */
export default class Outline2 {
  constructor ({
    sandbox,
    params = {},
    color
  }) {
    this.sandbox = sandbox
    this._color = color
    this._width = this.sandbox._width
    this._height = this.sandbox._height

    // 存储所有Outline实例的引用
    if (!sandbox._outlineInstances) {
      sandbox._outlineInstances = []
    }
    sandbox._outlineInstances.push(this)

    this._params = Object.assign({
      edgeStrength: 3.0,
      edgeGlow: 0.0,
      edgeThickness: 1.0,
      pulsePeriod: 5.0,
      usePatternTexture: false,
      visibleEdgeColor: this._color,
      hiddenEdgeColor: this._color
    }, params)

    // 初始化共享资源
    this.initSharedResources()

    // 创建自己的outlinePass
    this.createOutlinePass()
  }

  // 初始化共享资源
  initSharedResources () {
    const { renderer, scene, camera } = this.sandbox

    // 如果还没有创建composer，则创建
    if (!this.sandbox._outlineComposer) {
      this.sandbox._outlineComposer = new GC.EffectComposer(renderer)
      this.sandbox._outlineComposer.renderTarget1.samples = 8
      this.sandbox._outlineComposer.renderTarget2.samples = 8

      // 创建共享的renderPass
      this.sandbox._outlineRenderPass = new GC.RenderPass(scene, camera)
      this.sandbox._outlineComposer.addPass(this.sandbox._outlineRenderPass)

      // 存储所有outlinePass
      this.sandbox._outlinePasses = []

      // 添加输出通道
      this.sandbox._outlineOutputPass = new GC.OutputPass()

      // 启用后处理
      this.sandbox.enablePostProcessing = true

      // 添加渲染回调
      if (!this.sandbox._outlineRenderRegistered) {
        this._outlineComposerCallBack = () => {
          this.sandbox._outlineComposer.render()
        }
        this.sandbox.renderCalls.push(this._outlineComposerCallBack)

        this._outlineComposerCallBackSetSize = () => {
          this.sandbox._outlineComposer.setSize(this.sandbox._width, this.sandbox._height)
        }
        this.sandbox.sizeCalls.push(this._outlineComposerCallBackSetSize)

        // this.sandbox.renderCalls.push(() => {
        //   this.sandbox._outlineComposer.render()
        // })

        // this.sandbox.sizeCalls.push(() => {
        //   this.sandbox._outlineComposer.setSize(this.sandbox._width, this.sandbox._height)
        // })

        this.sandbox._outlineRenderRegistered = true
      }
    }
  }

  // 创建OutlinePass
  createOutlinePass () {
    this.outlinePass = new GC.OutlinePass(
      new GC.Vector2(this._width, this._height),
      this.sandbox.scene,
      this.sandbox.camera
    )

    // 设置参数
    this.outlinePass.edgeStrength = this._params.edgeStrength
    this.outlinePass.edgeGlow = this._params.edgeGlow
    this.outlinePass.edgeThickness = this._params.edgeThickness
    this.outlinePass.pulsePeriod = this._params.pulsePeriod
    this.outlinePass.visibleEdgeColor.set(this._params.visibleEdgeColor)
    this.outlinePass.hiddenEdgeColor.set(this._params.hiddenEdgeColor)

    if (this._params.usePatternTexture && this._params.patternTexture) {
      this.outlinePass.usePatternTexture = true
      this.outlinePass.patternTexture = this._params.patternTexture
    }
    if (!this.sandbox._outlinePasses) {
      this.sandbox._outlinePasses = []
    }
    // 添加到composer
    this.sandbox._outlinePasses.push(this.outlinePass)

    // 重新构建composer的passes
    this.rebuildComposer()
  }

  // 重新构建composer的passes
  rebuildComposer () {
    const { _outlineComposer, _outlineRenderPass, _outlinePasses, _outlineOutputPass } = this.sandbox

    // 清除所有pass
    _outlineComposer.passes = []

    // 添加renderPass
    _outlineComposer.addPass(_outlineRenderPass)

    // 添加所有outlinePass
    _outlinePasses.forEach(pass => {
      _outlineComposer.addPass(pass)
    })

    // 添加输出pass
    _outlineComposer.addPass(_outlineOutputPass)
  }

  // 更新参数
  updateParams (params = {}) {
    this._params = Object.assign(this._params, params)

    if (params.edgeStrength !== undefined) {
      this.outlinePass.edgeStrength = params.edgeStrength
    }
    if (params.edgeGlow !== undefined) {
      this.outlinePass.edgeGlow = params.edgeGlow
    }
    if (params.edgeThickness !== undefined) {
      this.outlinePass.edgeThickness = params.edgeThickness
    }
    if (params.pulsePeriod !== undefined) {
      this.outlinePass.pulsePeriod = params.pulsePeriod
    }
    if (params.visibleEdgeColor !== undefined) {
      this.outlinePass.visibleEdgeColor.set(params.visibleEdgeColor)
    }
    if (params.hiddenEdgeColor !== undefined) {
      this.outlinePass.hiddenEdgeColor.set(params.hiddenEdgeColor)
    }
    if (params.usePatternTexture !== undefined) {
      this.outlinePass.usePatternTexture = params.usePatternTexture
    }
    if (params.patternTexture !== undefined) {
      this.outlinePass.patternTexture = params.patternTexture
    }

    return this
  }

  // 添加对象到轮廓效果
  add (value) {
    if (!value) return this

    const addList = Array.isArray(value) ? value : [value]
    const selectedSet = new Set(this.outlinePass.selectedObjects)

    addList.forEach(obj => obj && selectedSet.add(obj))

    this.outlinePass.selectedObjects = Array.from(selectedSet)
    return this
  }

  // 从轮廓效果中移除对象
  remove (value) {
    if (!this.outlinePass.selectedObjects.length) return this

    const toRemove = new Set(
      Array.isArray(value) ? value : value ? [value] : []
    )

    this.outlinePass.selectedObjects =
      this.outlinePass.selectedObjects.filter(obj => !toRemove.has(obj))
    return this
  }

  // 清空所有对象
  clear () {
    this.outlinePass.selectedObjects = []
    return this
  }

  // 启用/禁用轮廓效果
  setEnabled (enabled) {
    this.outlinePass.enabled = enabled
    return this
  }

  // 获取当前选中的对象
  getSelectedObjects () {
    return [...this.outlinePass.selectedObjects]
  }

  // 销毁实例
  destroy () {
    this.outlinePass.selectedObjects = []
    this.outlinePass.enabled = false

    // 从实例列表中移除
    const instanceIndex = this.sandbox._outlineInstances.indexOf(this)
    if (instanceIndex !== -1) {
      this.sandbox._outlineInstances.splice(instanceIndex, 1)
    }

    // 从passes列表中移除
    const passIndex = this.sandbox._outlinePasses.indexOf(this.outlinePass)
    if (passIndex !== -1) {
      this.sandbox._outlinePasses.splice(passIndex, 1)
      this.rebuildComposer()
    }

    // 如果没有实例了，清理composer
    if (this.sandbox._outlineInstances.length === 0) {
      this.cleanupSharedResources()
    }
  }

  // 清理共享资源
  cleanupSharedResources () {
    // if (this.sandbox._outlineComposer) {
    //   this.sandbox._outlineComposer.dispose()
    //   this.sandbox._outlineComposer = null
    // }
    // this.sandbox._outlineComposer.passes.forEach((pass) => {

    // })
    // this.sandbox._outlineComposer.removePass(this.sandbox._outlineOutputPass)
    // this.sandbox._outlineComposer.removePass(this.sandbox._outlineRenderPass)
    // console.log(this.sandbox._outlineComposer)
    // this.sandbox._outlineComposer.dispose()
    // this.sandbox._outlineComposer = null

    if (this.sandbox._outlineRenderPass) {
      this.sandbox._outlineRenderPass.dispose()
      this.sandbox._outlineRenderPass = null
    }

    if (this.sandbox._outlineOutputPass) {
      this.sandbox._outlineOutputPass.dispose()
      this.sandbox._outlineOutputPass = null
    }

    this.sandbox._outlinePasses = null

    // 移除渲染回调
    if (this.sandbox._outlineRenderRegistered) {
      // const renderIndex = this.sandbox.renderCalls.findIndex(cb => cb.toString().includes('_outlineComposer'))
      // if (renderIndex !== -1) {
      //   this.sandbox.renderCalls.splice(renderIndex, 1)
      // }

      // const sizeIndex = this.sandbox.sizeCalls.findIndex(cb => cb.toString().includes('_outlineComposer'))
      // if (sizeIndex !== -1) {
      //   this.sandbox.sizeCalls.splice(sizeIndex, 1)
      // }

      const renderIndex = this.sandbox.renderCalls.indexOf(this._outlineComposerCallBack)
      if (renderIndex > -1) {
        this.sandbox.renderCalls.splice(renderIndex, 1) // 从找到的索引位置移除1个元素
      }

      const sizeIndex = this.sandbox.renderCalls.indexOf(this._outlineComposerCallBackSetSize)
      if (sizeIndex > -1) {
        this.sandbox.renderCalls.splice(sizeIndex, 1) // 从找到的索引位置移除1个元素
      }

      this.sandbox._outlineRenderRegistered = false
    }
  }
}
